package com.MoveEat.activities;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.osmdroid.util.GeoPoint;

import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.text.util.Linkify;
import android.util.Pair;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.MoveEat.R;
import com.MoveEat.Utils.Consts;
import com.MoveEat.Utils.SimplePhotoCache;
import com.MoveEat.Utils.Utils;
import com.MoveEat.activities.adapters.AwesomePagerAdapter;
import com.MoveEat.activities.adapters.MoveEatViewGalleryAdapter;
import com.MoveEat.views.CommentDialog;
import com.MoveEat.views.MenuHandler;
import com.MoveEat.views.RestMap;
import com.MoveEat.views.ViewPagerIndicator;

public class NewRestActivity extends ActivityWrapper
{

	// private MoveEatGallery mTabGallery;
	// private ViewStub viewStub;
	private long									mRestId;
	private SimplePhotoCache						photos;
	private int										mCount;
	private ArrayList<String>						mTitleArray;
	private MoveEatViewGalleryAdapter				mViewGalleryAdapter;
	private ArrayList<MenuHandler>					menuHandlers;
	private HashMap<Integer, Pair<Long, String>>	mMenuIds;
	private View									mRestView;
	// private MoveEatGallery mViewGallery;
	private RestMap									mMapView;
	private HashMap<Integer, String>				mCatHashMap;
	private int										mMoveEatUID;

	private JSONArray								mRestDetails;
	private JSONArray								mRestProps;
	private int										mOrientation;
	private ViewPagerIndicator						mIndicator;
	private ViewPager								mViewPager;

	@SuppressWarnings("unchecked")
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
		photos = new SimplePhotoCache(getBaseContext().getResources().getDrawable(R.drawable.icon));
		mOrientation = display.getOrientation();
		setContentView(R.layout.rest_details_layout);
		mViewPager = (ViewPager) findViewById(R.id.awesomepager);
		Intent intent = getIntent();
		mRestId = intent.getLongExtra(Consts.Extras.REST_ID, -1);
		mCatHashMap = ((HashMap<Integer, String>) intent.getSerializableExtra(Consts.Extras.CATS));
		mMoveEatUID = intent.getIntExtra(Consts.Extras.ME_UID, -1);
		mIndicator = (ViewPagerIndicator) findViewById(R.id.indicator);
		mViewPager.setOnPageChangeListener(mIndicator);
		Resources res = getResources();
		Drawable prev = res.getDrawable(R.drawable.indicator_prev_arrow);
		Drawable next = res.getDrawable(R.drawable.indicator_next_arrow);
		mIndicator.setArrows(prev, next);

		if (mRestId >= 0)
		{
			Utils.log(1,"getting Rest Details");
			getRestDetails();
		}
		else
		{
			finish();
		}

		mTitleArray = new ArrayList<String>();
		mTitleArray.add(getString(R.string.map));
		mTitleArray.add(getString(R.string.info));

	}

	private void getMenuDetails()
	{
		menuHandlers = new ArrayList<MenuHandler>();
		for (int i = 0; i < mCount; i++)
		{
			menuHandlers.add(new MenuHandler(mRestId, this, "", mMenuIds.get(i).second, mMenuIds.get(i).first, mCatHashMap));
		}

	}

	private void getRestDetails()
	{
		new AsyncTask<Void, String, String>()
		{

			@Override
			protected void onPreExecute()
			{
				NewRestActivity.this.showLoading(this);
			}

			@Override
			protected String doInBackground(Void... arg0)
			{
				String menuReq = Utils.preformRequest(Utils.BASE_URL + "GetMenus.php?rest_id=" + mRestId + "&count=true");
				if (menuReq != null)
				{
					Utils.log(2,menuReq);
					setMenuIds(menuReq);
				}
				return (Utils.preformRequest(Utils.BASE_URL + "GetRestDetails.php?id=" + mRestId + "&menu_count=true"));
			}

			@Override
			protected void onPostExecute(String body)
			{
				Utils.log(2,body);
				if (body != null)
				{
					JSONObject obj = null;
					try
					{
						obj = new JSONObject(body);
					}
					catch (JSONException e)
					{
						Utils.log(-1,"Error creating JSON: " + e.getMessage());
					}
					if (obj != null)
					{
						mRestDetails = obj.optJSONArray("restaurants");
						mRestProps = obj.optJSONArray("properties");
						setMenuNames();
						mRestView = displayRestDetails(mRestDetails, mRestProps);
						getMenuDetails();
						mViewGalleryAdapter = new MoveEatViewGalleryAdapter(NewRestActivity.this.getBaseContext(), mCount, menuHandlers, mRestView, mMapView);
						AwesomePagerAdapter adapter = new AwesomePagerAdapter(mCount, menuHandlers, mRestView, mMapView);
						mViewPager.setAdapter(adapter);
						mIndicator.init(100, mCount + 2, NewRestActivity.this);
						mIndicator.setMenuNames(mTitleArray);
						mIndicator.invalidate();
						mViewPager.setCurrentItem(1);
						mViewPager.refreshDrawableState();

					}
					else
					{

					}

					removeDialog(ProgressDialog.STYLE_HORIZONTAL);
				}
			}

		}.execute();
		mIndicator.setOnClickListener(new ViewPagerIndicator.OnClickListener()
		{

			@Override
			public void onPreviousClicked(View v)
			{
				mViewPager.setCurrentItem(mIndicator.getCurrentPosition() - 1);

			}

			@Override
			public void onNextClicked(View v)
			{
				mViewPager.setCurrentItem(mIndicator.getCurrentPosition() + 1);

			}

			@Override
			public void onCurrentClicked(View v)
			{
				// TODO Auto-generated method stub

			}
		});

	}

	protected void setMenuIds(String menuIds)
	{
		try
		{
			JSONObject obj = new JSONObject(menuIds);
			JSONArray arr = obj.optJSONArray("menus");
			mMenuIds = new HashMap<Integer, Pair<Long, String>>();
			for (int i = 0; i < arr.length(); i++)
			{
				JSONObject currObj = arr.optJSONObject(i);
				mMenuIds.put(i, new Pair<Long, String>(Long.parseLong(currObj.optString("MENU_ID")), currObj.optString("MENU_NAME")));
			}
			mCount = arr.length();
		}
		catch (JSONException e)
		{
			e.printStackTrace();
		}

	}

	protected void setMenuNames()
	{
		for (int i = 0; i < mCount; i++)
		{
			mTitleArray.add(mMenuIds.get(i).second);

		}
	}

	private View displayRestDetails(JSONArray arr, JSONArray propArr)
	{
		// viewStub.inflate();
		LayoutInflater inflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = null;
		if (mOrientation == Configuration.ORIENTATION_PORTRAIT)
		{
			view = inflater.inflate(R.layout.restaurant_layout, null);
		}
		else
		{
			view = inflater.inflate(R.layout.restaurant_layout_land, null);
		}
		Button commentsBtn = (Button) view.findViewById(R.id.comment_button);

		for (int i = 0; i <= arr.length() - 1; i++)
		{
			JSONObject rest = arr.optJSONObject(i);
			String phone2 = "";
			String imageUrl = null;

			TextView restName = (TextView) view.findViewById(R.id.txtRestName);
			TextView restAddress = (TextView) view.findViewById(R.id.txtRestAddress);
			TextView restPhone = (TextView) view.findViewById(R.id.txtRestPhone);
			TextView restPhone2 = (TextView) view.findViewById(R.id.txtRestPhone2);
			TextView hoursText = (TextView) view.findViewById(R.id.hours_text);
			TextView costText = (TextView) view.findViewById(R.id.cost_from_to_text);
			ImageView restImage = (ImageView) view.findViewById(R.id.restImg);

			// long mId = rest.optLong(Consts.DB_COLUMNS.ID);
			final String name = rest.optString(Consts.DB_COLUMNS.NAME);
			String address = rest.optString(Consts.DB_COLUMNS.STREET) + " " + rest.optString(Consts.DB_COLUMNS.STREET_NUM) + ", "
					+ rest.optString(Consts.DB_COLUMNS.CITY);
			String phone = rest.optString(Consts.DB_COLUMNS.PHONE);
			if (rest.optString(Consts.DB_COLUMNS.SECONDARY_PHONE) != null) phone2 = rest.optString(Consts.DB_COLUMNS.SECONDARY_PHONE);
			if (rest.optString(Consts.DB_COLUMNS.IMAGE_URL) != null)
			{
				imageUrl = Consts.IMAGE_PATH + rest.optString(Consts.DB_COLUMNS.IMAGE_URL);
			}
			if (!TextUtils.isEmpty(imageUrl) && !imageUrl.equals("null") && imageUrl.contains("http"))
			{
				photos.loadPhoto(imageUrl, restImage);
			}
			GeoPoint gPoint = new GeoPoint(Double.parseDouble(rest.optString(Consts.DB_COLUMNS.LATITUDE)), Double.parseDouble(rest
					.optString(Consts.DB_COLUMNS.LONGITUDE)));
			mMapView = new RestMap(this, gPoint, address);

			restName.setText(name);

			commentsBtn.setOnClickListener(new View.OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					new CommentDialog(NewRestActivity.this, mMoveEatUID, name, mRestId, NewRestActivity.this).show();
				}
			});
			restAddress.setClickable(true);
			restAddress.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=" + ((TextView) v).getText()));
					try
					{
						startActivity(intent);
					}
					catch (ActivityNotFoundException ex)
					{
						Toast.makeText(getBaseContext(), "Google Maps is not installed", Toast.LENGTH_LONG).show();
					}
				}
			});
			restAddress.setText(address);
			restPhone.setText(phone);
			Linkify.addLinks(restPhone, Linkify.PHONE_NUMBERS);
			Linkify.addLinks(restPhone2, Linkify.PHONE_NUMBERS);
			if (!TextUtils.isEmpty(phone2))
			{
				restPhone2.setText(phone2);
			}
			else
			{
				// RelativeLayout.LayoutParams params = (LayoutParams)
				// hoursText.getLayoutParams();
				// params.addRule(RelativeLayout.BELOW, restPhone.getId());
				// hoursText.setLayoutParams(params);
				restPhone2.setVisibility(View.GONE);
			}
			hoursText.setText(getHoursText(rest));
			costText.setText(getCosts(rest));
		}
		if (propArr != null)
		{
			for (int i = 0; i < propArr.length(); i++)
			{
				switch (Integer.parseInt(propArr.optJSONObject(i).optString("PROPERTY_ID")))
				{

					case Consts.PROPERTIES.DELIVERY:
						((CheckBox) view.findViewById(R.id.delivery_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.KOSHER:
						((CheckBox) view.findViewById(R.id.kosher_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.KOSHER_MEHADRIN:
						((CheckBox) view.findViewById(R.id.kosher_mehadrin_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.DIS_ACCESS:
						((CheckBox) view.findViewById(R.id.dis_acc_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.CHILD_FRIEND:
						((CheckBox) view.findViewById(R.id.child_friendly_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.EVENT_OK:
						((CheckBox) view.findViewById(R.id.event_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.ROMANTIC:
						((CheckBox) view.findViewById(R.id.romantic_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.CONCERTS:
						((CheckBox) view.findViewById(R.id.concerts_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.OUT_SIDE:
						((CheckBox) view.findViewById(R.id.out_side_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.PARKING:
						((CheckBox) view.findViewById(R.id.parking_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.SMOKING:
						((CheckBox) view.findViewById(R.id.smoking_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.CATERING:
						((CheckBox) view.findViewById(R.id.catering_checkbox)).setChecked(true);
						break;

					case Consts.PROPERTIES.WIRELESS:
						((CheckBox) view.findViewById(R.id.wireless_checkbox)).setChecked(true);
						break;

				}
			}
		}
		return view;

	}

	private CharSequence getCosts(JSONObject rest)
	{
		String costFrom = rest.optString(Consts.DB_COLUMNS.COST_FROM);
		String costTo = rest.optString(Consts.DB_COLUMNS.COST_TO);
		if (costFrom.equals("null"))
		{
			costFrom = "";
		}
		if (costTo.equals("null"))
		{
			costTo = "";
		}
		return getString(R.string.costs) + costFrom + " - " + costTo;
	}

	private String getHoursText(JSONObject rest)
	{
		String weekOpen = rest.optString(Consts.DB_COLUMNS.WEEKDAY_OPENING_HOUR);
		String weekClose = rest.optString(Consts.DB_COLUMNS.WEEKDAY_CLOSING_HOUR);
		String fridayOpen = rest.optString(Consts.DB_COLUMNS.FRIDAY_OPENING_HOUR);
		String fridayClose = rest.optString(Consts.DB_COLUMNS.FRIDAY_CLOSING_HOUR);
		String satOpen = rest.optString(Consts.DB_COLUMNS.SATURDAY_OPENING_HOUR);
		String satClose = rest.optString(Consts.DB_COLUMNS.SATURDAY_CLOSING_HOUR);
		StringBuilder str = new StringBuilder();
		str.append(getString(R.string.sunday_thursday) + " ");
		str.append(getTime(weekOpen, weekClose)).append("\n");
		str.append(getString(R.string.friday) + " ").append(getTime(fridayOpen, fridayClose)).append("\n");
		str.append(getString(R.string.saturday) + " ").append(getTime(satOpen, satClose));
		return str.toString();

	}

	private String getTime(String timeOpen, String timeClose)
	{
		String timeOpenRes = "";
		String timeCloseRes = "";
		if (!TextUtils.isEmpty(timeOpen) && !timeOpen.equals("null"))
		{
			timeOpenRes = timeOpen.substring(0, 5);
			if (!TextUtils.isEmpty(timeClose) && !timeClose.equals("null"))
			{
				timeCloseRes = timeClose.substring(0, 5);
			}
			else
			{
				timeCloseRes = getString(R.string.till_last_customer);
			}
		}
		if (timeOpenRes.equals(""))
		{
			return getString(R.string.close);
		}
		else
		{
			return timeOpenRes + " - " + timeCloseRes;
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig)
	{
		mOrientation = newConfig.orientation;
		if (mRestDetails != null && mRestProps != null)
		{
			mRestView = displayRestDetails(mRestDetails, mRestProps);
			mViewGalleryAdapter.setRestView(mRestView);
			mViewGalleryAdapter.notifyDataSetChanged();
			mViewPager.invalidate();
		}
		super.onConfigurationChanged(newConfig);

	}

}
